<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">年级</label>
                            <div class="layui-input-inline">
                                <select name="grade" lay-verify="" id="grade-select-search">
                                    <option value="">请选择一个年级</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">学院</label>
                            <div class="layui-input-inline">
                                <select name="college" lay-verify="" id="college-select-search" lay-filter="college-select-search">
                                    <option value="">请选择一个学院</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">专业</label>
                            <div class="layui-input-inline">
                                <select name="major" lay-verify="" id="major-select-search">
                                    <option value="">需要先选择学院</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
<!--            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>-->
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>

<script>
    layui.use(['form', 'table', 'miniPage', 'element'], function() {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            miniPage = layui.miniPage;

        //学院选择
        jq1111.ajax({
            type: "GET",
            crossDomain: true,
            url: BasePath+"api/School/Colleges",
            contentType: "application/json",
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            success: function(message) {
                var colleges = message.data;
                console.log(message);
                colleges.forEach(function(college) {
                        console.log(college)
                        jq1111("#college-select-search").append('' +
                            '<option value="' +
                            college.id +
                            '">' +
                            college.name +
                            '</option>' +
                            '')
                    })
                    //再次初始化form
                form.render();
            },
            error: function(message) {
                console.log(message.responseJSON);
                layer.msg('失败:' + message.responseJSON.message);
            },
        });

        //年级选择
        jq1111.ajax({
            type: "GET",
            crossDomain: true,
            url: BasePath+"api/School/Grades",
            contentType: "application/json",
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            success: function(message) {
                console.log(message)
                var grades = message.data;
                grades.forEach(function(grade) {
                        jq1111("#grade-select-search").append('' +
                            '<option value="' +
                            grade.id +
                            '">' +
                            grade.display +
                            '</option>' +
                            '')
                    })
                    //再次初始化form
                form.render();
            },
            error: function(message) {
                console.log(message.responseJSON);
                layer.msg('失败:' + message.responseJSON.message);
            },
        });

        //监听学院的select事件来获取专业
        form.on('select(college-select-search)', function(data){
            console.log(data)
            if(data.value == ""){
                jq1111("#major-select-search").attr("disabled","disabled");
                jq1111("#class-select-search").attr("disabled","disabled");

                form.render('select');
            }else{
                jq1111("#major-select-search").removeAttr("disabled");
                //移除之前添加的专业
                var children=jq1111("#major-select-search").children();
                for (i=1;i<children.length;i++){
                    children.eq(i).remove();
                }
                //获取专业
                jq1111.ajax({
                    type: "GET",
                    crossDomain:true,
                    url: BasePath+"api/School/Majors?collegeId="+data.value,
                    contentType: "application/json",
                    dataType:"json",
                    xhrFields: {
                        withCredentials: true
                    },
                    success:function (message) {
                        var majors=message.data;
                        majors.forEach(function (major) {
                            jq1111("#major-select-search").append('' +
                                '<option value="' +
                                major.id +
                                '">' +
                                major.name +
                                '</option>' +
                                '')
                        });
                        //再次初始化form
                        form.render('select');
                    },
                    error:function (message) {
                        console.log(message.responseJSON);
                    },
                });
                form.render('select');//select是固定写法 不是选择器
            }
        });


        table.render({
            elem: '#currentTableId',
            url: BasePath+'api/School/Classes?majorId=1',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [
                [{
                        type: "checkbox",
                        width: 50
                    }, {
                        field: 'id',
                        width: 80,
                        title: 'ID',
                        sort: true
                    }, {
                        field: 'name',
                        width: 200,
                        title: '班级名'
                    }, {
                        field: 'studentCount',
                        width: 80,
                        title: '人数',
                        sort: true
                    },
                    // {field: 'college', width: 200, title: '学院'},
                    // {field: 'grade.display', title: '年级', minWidth: 150},
                    {
                        field: 'albumCount',
                        title: '相册数',
                        minWidth: 150
                    }, {
                        title: '操作',
                        minWidth: 180,
                        toolbar: '#currentTableBar',
                        align: "center"
                    }
                ]
            ],
            // limits: [10, 15, 20, 25, 50, 100],
            // limit: 15,
            // page: true,
            skin: 'line'
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function(data) {
            var result = JSON.stringify(data.field);

            if (data.field.major === "" || data.field.grade === "") {
                layer.alert('参数不全，请检查检索条件', {
                    title: '参数不全，请检查检索条件'
                });
                return false;
            }
            console.log(data)
                //执行搜索重载
            table.reload('currentTableId', {
                url: BasePath+'api/School/QueryClasses?majorId=' + data.field.major + '&gradeId=' + data.field.grade,
            }, 'data');

            return false;
        });

        /**
         * toolbar事件监听
         */
        table.on('toolbar(currentTableFilter)', function(obj) {
            if (obj.event === 'add') { // 监听添加操作
                var content = miniPage.getHrefContent('page/admin/classes-setting/add.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '添加班级',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                });
                $(window).on("resize", function() {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') { // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId'),
                    data = checkStatus.data;
                if (data.length === 0) {
                    layer.alert('未选择要删除的数据', {
                        title: '操作不合法'
                    });
                    return;
                }
                var deletedItemCount = 0;
                data.forEach(function(deleteData) {
                    if (deleteClass(deleteData.id)) {
                        deletedItemCount++;
                    }
                });
                layer.alert('成功删除' + deletedItemCount + '个数据,' + (data.length - deletedItemCount) + '条删除失败，如果存在删除失败，请尝试刷新界面重试', {
                    title: '操作结果'
                });
                table.reload('currentTableId', {}, 'data');
                console.log(data)
            } else if (obj.event === 'setting') { // 设置删除操作
                var content = miniPage.getHrefContent('page/admin/classes-setting/setting.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '班级设置',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                });
                $(window).on("resize", function() {
                    layer.full(index);
                });
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function(obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function(obj) {
            var data = obj.data;
            if (obj.event === 'edit') {
                console.log(data)
                var content = miniPage.getHrefContent('page/admin/classes-setting/edit.html' + '?id=' + data.id);
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '编辑班级',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                });
                $(window).on("resize", function() {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('真的删除行么', function(index) {
                    console.log(data)
                    jq1111.ajax({
                        type: "POST",
                        crossDomain: true,
                        url: BasePath+"api/School/RemoveClass",
                        contentType: "application/json",
                        dataType: "json",
                        data: JSON.stringify({
                            "majorId": data.grade.id,
                            "classId": data.id
                        }),
                        xhrFields: {
                            withCredentials: true
                        },
                        success: function(message) {
                            console.log(message)
                            obj.del();
                            layer.msg(message.msg);
                        },
                        error: function(message) {
                            console.log(message.responseJSON);
                            layer.msg('失败:' + message.responseJSON.msg);
                        },
                    });
                    layer.close(index);
                });
            }
        });

        function deleteClass(classId) {
            var result=false;
            jq1111.ajax({
                type: "POST",
                crossDomain: true,
                url: BasePath+"api/School/RemoveClass",
                contentType: "application/json",
                dataType: "json",
                async:false,
                data: JSON.stringify({
                    "classId": classId
                }),
                xhrFields: {
                    withCredentials: true
                },
                success: function(message) {
                    result = true;
                },
                error: function(message) {
                    console.log(message.responseJSON);
                    result = false;
                },
            });
            return result;
        }

    });
</script>